﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Bll.DTO.UserInfo;
using CSP.Common.Tools;
using CSP.Model.CSPEnum;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using CSP.Model.CSPBBS;
using System.Configuration;
using CSP.Common.Factories;
using CSP.Common.Web;
using System.Net;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using CSP.Common.IProviders;

namespace CSP.Web.UCenter
{
    public partial class OtherLogin : CSPMainPageBase
    {
        private const string SESSIONNAMEKEY = "ScreenName";

        private const string SESSIONOTHERID = "OtherId";

        private const string SESSIONOTHERTYPE = "OtherType";

        /// <summary>
        /// 登陆类型
        /// </summary>
        private UserLoginType UserLoginType
        {
            get
            {
                if (Session["UserLoginType"] != null)
                {
                    return (UserLoginType)Session["UserLoginType"];
                }
                return UserLoginType.Common;
            }
            set
            {
                Session["UserLoginType"] = value;
            }
        }

        /// <summary>
        /// 第三方的登陆Code值
        /// </summary>
        private string OtherCode
        {
            get
            {
                if (Session["OtherCode"] != null)
                {
                    return Session["OtherCode"].ToString();
                }
                return "";
            }
            set
            {
                Session["OtherCode"] = value;
            }
        }


        /// <summary>
        /// 用户登陆信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private Dictionary<string, string> OtherUserInfo
        {
            get
            {
                if (Session["OtherUserInfo"] != null)
                {
                    return (Dictionary<string, string>)Session["OtherUserInfo"];
                }
                return null;
            }
            set
            {
                Session["OtherUserInfo"] = value;
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request["code"] != null && Request[SESSIONOTHERTYPE] != null)
                {
                        OtherLoginSuccess();
                }
                else if (Request[SESSIONOTHERTYPE] != null)
                {
                    RedirectOtherLogin();
                }
                else if (Request["checkname"] != null) //用户名验证
                {
                    //string aa = this.Txt_UserName.Name;
                    if (Request[this.Txt_Other_Name.Name] != null && Request["checkname"] != null)
                    {
                        CheckUniqueByUserName(Request[this.Txt_Other_Name.Name].ToString());
                    }
                }
                
            }


        }


        /// <summary>
        /// 跳转到第三方登陆授权
        /// </summary>
        private void RedirectOtherLogin()
        { 
            UserLoginType = (UserLoginType)Convert.ToInt32(Request[SESSIONOTHERTYPE].ToString());
            string url = GetOtherLoginBackUrl();
            //string currentUrl = Server.UrlEncode(url);
           

            switch (UserLoginType)
            {
                case UserLoginType.SinaWeiBo:
                    //请求新浪登陆授权
                    OtherApiFactory.GetSinaApi().RequestApiAuthorization(url);
                    break;
                case UserLoginType.QQConnect:
                    OtherApiFactory.GetQQConnectApi().RequestApiAuthorization(url);
                    break;
                case UserLoginType.TencentWeiBo:
                    OtherApiFactory.GetTencentWeiBoApi().RequestApiAuthorization(url);
                    break;
                case UserLoginType.RenRen:
                    OtherApiFactory.GetRenRenApi().RequestApiAuthorization(url);
                    break;
            }
        }


        /// <summary>
        /// 第三方登陆授权成功
        /// </summary>
        protected void OtherLoginSuccess()
        {
            bool bl = false;
            try
            {
                //获取第三方token
                string accessToken = GetOtherToken();

                //根据token本地化验证
                bl=LocalCheck(accessToken);
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(UserLoginType, ex);
                this.FailRedirect("第三方登陆暂时拥堵,请重试或信然贷账号登陆", "/Ucenter/login.aspx?urlback=" + Server.UrlEncode(Request["urlback"].ToString()));
            }

            //所有验证成功跳转指定页面
            if (bl&&Request["urlback"] != null)
            {
                Response.Redirect(Request["urlback"].ToString());
            }

            MakeImageByOtherType();

        }

        /// <summary>
        /// 获取第三方token
        /// </summary>
        private string GetOtherToken()
        {
            string accessToken = "";
            if ((OtherUserInfo == null || !string.IsNullOrWhiteSpace(OtherCode)) && OtherCode != Request["code"].ToString())
            {

                string code = OtherCode = Request["code"].ToString();
                string url = GetOtherLoginBackUrl();
                //UserLoginType = (UserLoginType)Convert.ToInt32(Request[SESSIONOTHERTYPE].ToString());
                switch (UserLoginType)
                {
                    case UserLoginType.SinaWeiBo:
                        OtherApiProvider sinaWeiBoApiProvider = OtherApiFactory.GetSinaApi();
                        OtherUserInfo = sinaWeiBoApiProvider.GetUserInfo(code, url);
                        accessToken = sinaWeiBoApiProvider.AccessToken;
                        break;
                    case UserLoginType.QQConnect:
                        OtherApiProvider qqConnectApiProvider = OtherApiFactory.GetQQConnectApi();
                        OtherUserInfo = qqConnectApiProvider.GetUserInfo(code, url);
                        accessToken = qqConnectApiProvider.AccessToken;
                        break;
                    case UserLoginType.TencentWeiBo:
                        OtherApiProvider tencentWeiboApiProvider = OtherApiFactory.GetTencentWeiBoApi();
                        string openId = Request["openId"].ToString();
                        OtherUserInfo = tencentWeiboApiProvider.GetUserInfo(code, url, openId);
                        accessToken = tencentWeiboApiProvider.AccessToken;
                        break;
                    case UserLoginType.RenRen:
                        OtherApiProvider renrenProvider = OtherApiFactory.GetRenRenApi();
                        OtherUserInfo = renrenProvider.GetUserInfo(code, url);
                        accessToken = renrenProvider.AccessToken;
                        break;
                }
            }

            return accessToken;
        }

        /// <summary>
        /// 本地化验证
        /// </summary>
        /// <param name="accessToken"></param>
        private bool LocalCheck(string accessToken)
        {
            bool result = false;
            //验证是否已经注册授权过了
            switch (UserLoginType)
            {
                case UserLoginType.SinaWeiBo:
                    result=AuthOtherLogin(UserLoginType, OtherUserInfo["id"], OtherUserInfo["screen_name"], OtherUserInfo["profile_image_url"], accessToken);
                    break;
                case UserLoginType.QQConnect:
                    result=AuthOtherLogin(UserLoginType, OtherApiFactory.GetQQConnectApi().Uid, OtherUserInfo["nickname"], OtherUserInfo["figureurl_2"], accessToken);
                    break;
                case UserLoginType.TencentWeiBo:
                    result=AuthOtherLogin(UserLoginType, OtherApiFactory.GetTencentWeiBoApi().Uid, OtherUserInfo["nick"], OtherUserInfo["head"], accessToken);
                    break;
                case UserLoginType.RenRen:
                    result = AuthOtherLogin(UserLoginType, OtherApiFactory.GetRenRenApi().Uid, OtherUserInfo["name"], OtherUserInfo["headurl"], accessToken);
                    break;
            }
            return result;
        }


        /// <summary>
        /// 第三方登陆验证
        /// </summary>
        private bool AuthOtherLogin(UserLoginType userLoginType, string otherId, string screenName, string profileUrl, string accessToken = "")
        {
            bool result = false;
            Member member = null;
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            using (IUserInfoBll userInfoBll = bllFactory.GetUserInfoBll())
            {
                member = userInfoBll.OtherLogin(userLoginType, otherId, accessToken);
            }

            if (member == null)
            {
                this.Bind_OtherNoHaving_Avatar.Src = profileUrl;
                this.Txt_Other_Name.Value = screenName;
                this.OtherNoHavingScreenName.InnerText = screenName;
            }
            else
            {
                result = true;
                Session["UserName"] = member.UserName.Trim();
                Session["Uid"] = member.Id;
                CreateCookieByMember(member.Id, member.CommonMember.PassWord, DateTime.Now.AddHours(2));
            
            }
            return result;
        }

        protected void Btn_OtherLogin_Click(object sender, EventArgs e)
        {
            string name = this.Txt_Other_Name.Value;
            string email = this.Txt_Other_Email.Value;
            OtherRegisterDTO request = new OtherRegisterDTO();
            request.Email = email;


            if (OtherUserInfo == null)
            {
                Alert("抱歉,未检测到有第三方登陆信息!");
                return;
            }

            switch (UserLoginType)
            {
                case UserLoginType.SinaWeiBo:
                    request.Screen_Name = OtherUserInfo["screen_name"].ToString();
                    request.OtherIdentity = OtherApiFactory.GetSinaApi().Uid;
                    request.Token = OtherApiFactory.GetSinaApi().AccessToken;
                    break;
                case UserLoginType.QQConnect:
                    request.Screen_Name = OtherUserInfo["nickname"].ToString();
                    request.OtherIdentity = OtherApiFactory.GetQQConnectApi().Uid;
                    request.Token = OtherApiFactory.GetQQConnectApi().AccessToken;
                    break;
                case UserLoginType.TencentWeiBo:
                    request.Screen_Name = OtherUserInfo["nick"].ToString();
                    request.OtherIdentity = OtherApiFactory.GetTencentWeiBoApi().Uid;
                    request.Token = OtherApiFactory.GetTencentWeiBoApi().AccessToken;
                    break;
                case UserLoginType.RenRen:
                    request.Screen_Name = OtherUserInfo["name"].ToString();
                    request.OtherIdentity = OtherApiFactory.GetRenRenApi().Uid;
                    request.Token = OtherApiFactory.GetRenRenApi().AccessToken;
                    break;
            }

            request.UserName = name;
            
            request.IP = CommonTool.GetIP();
            request.UserLoginType = (UserLoginType)Convert.ToInt32(Request[SESSIONOTHERTYPE].ToString());

            Member member = null;
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            using (IUserInfoBll userInfoBll = bllFactory.GetUserInfoBll())
            {
                member = userInfoBll.OtherRegister(request);
            }
            if (member != null)
            {
                Session["UserName"] = member.UserName.Trim();
                Session["Uid"] = member.Id;
                CreateCookieByMember(member.Id, member.CommonMember.PassWord, DateTime.Now.AddHours(2));
            }

            //第三方事件处理 例如加关注，发布微博
            OtherEventHandling();

            if (Request["urlback"] != null)
            {
                Response.Redirect(Request["urlback"].ToString());
            }

        }

        private void OtherEventHandling()
        {
            switch (UserLoginType)
            {

                //新浪微博处理
                case UserLoginType.SinaWeiBo:
                    SinaEventHandling();
                    break;
                //QQ互联处理
                case UserLoginType.QQConnect:
                    QQConnectEventHandling();
                    break;
                //腾讯微博
                case UserLoginType.TencentWeiBo:
                    TencentEventHandling();
                    break;
                //人人
                case UserLoginType.RenRen:
                    RenRenEventHandling();
                    break;
            }
        }

        /// <summary>
        /// 新浪事件处理 关注+发布微博
        /// </summary>
        private void SinaEventHandling()
        {
            string accessToken = "";
            string uid = "";
            try
            {
                bool isPublish = Check_Publish.Checked;
                bool isAttention = Check_Attention.Checked;

                //调用新浪微博Api
                OtherApiProvider apiProvider = OtherApiFactory.GetSinaApi();
                accessToken = apiProvider.AccessToken;
                uid = apiProvider.Uid;
                apiProvider.EventHandling(isPublish, isAttention);
            }
            catch (Exception ex)
            {
                LoggerProvider.Warn("警告新浪微博发布或关注错误!" + " uid:" + uid + " AccessToken:(" + accessToken + ")", ex);
            }

        }

        private void QQConnectEventHandling()
        {
            string accessToken = "";
            string uid = "";
            try
            {
                bool isPublish = Check_Publish.Checked;
                bool isAttention = Check_Attention.Checked;

                //调用腾讯QQ互联Api
                OtherApiProvider apiProvider = OtherApiFactory.GetQQConnectApi();
                accessToken = apiProvider.AccessToken;
                uid = apiProvider.Uid;
                apiProvider.EventHandling(isPublish, isAttention);
            }
            catch (Exception ex)
            {
                LoggerProvider.Warn("警告QQ互联发布或关注错误!" + " uid:" + uid + " AccessToken:(" + accessToken + ")", ex);
            }
        }

        private void TencentEventHandling() 
        {
            string accessToken = "";
            string uid = "";
            try
            {
                bool isPublish = Check_Publish.Checked;
                bool isAttention = Check_Attention.Checked;

                //调用腾讯QQ互联Api
                OtherApiProvider apiProvider = OtherApiFactory.GetTencentWeiBoApi();
                accessToken = apiProvider.AccessToken;
                uid = apiProvider.Uid;
                apiProvider.EventHandling(isPublish, isAttention);
            }
            catch (Exception ex)
            {
                LoggerProvider.Warn("警告腾讯微博发布或关注错误!" + " uid:" + uid + " AccessToken:(" + accessToken + ")", ex);
            }
        }

        private void RenRenEventHandling()
        {
            string accessToken = "";
            string uid = "";
            try
            {
                bool isPublish = Check_Publish.Checked;
                bool isAttention = Check_Attention.Checked;

                //调用腾讯QQ互联Api
                OtherApiProvider apiProvider = OtherApiFactory.GetRenRenApi();
                accessToken = apiProvider.AccessToken;
                uid = apiProvider.Uid;
                apiProvider.EventHandling(isPublish, isAttention);
            }
            catch (Exception ex)
            {
                LoggerProvider.Warn("警告人人发布或关注错误!" + " uid:" + uid + " AccessToken:(" + accessToken + ")", ex);
            }
        }
        /// <summary>
        /// 创建cookie
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <param name="expires"></param>
        private void CreateCookieByMember(int uid, string pwd, DateTime expires)
        {
            string saltkey = CommonTool.GenerateCode(8);
            string authKey = CommonTool.MD5(ConfigurationManager.AppSettings["AuthKey"].ToString() + saltkey);
            string cookieAuth = CommonTool.DiscuzAuthcodeEncode(pwd + "\t" + uid.ToString(), authKey);

            CookieFactory factory = CookieFactory.GetInstace();
            factory.Expires = expires;
            factory.SetCookie(this, "saltkey", saltkey);
            factory.SetCookie(this, "auth", cookieAuth);
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private bool IsExsitByUserName(string userName)
        {
            bool result = false;
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            using (IUserInfoBll userInfoBll = bllFactory.GetUserInfoBll())
            {
                result = userInfoBll.IsExsitByUserName(userName.Trim());
            }
            return result;
        }

        /// <summary>
        /// 验证用户名是否重复
        /// </summary>
        protected void CheckUniqueByUserName(string userName)
        {
            bool checkValue = IsExsitByUserName(userName);

            Response.ClearContent();
            if (checkValue)
            {
                Response.Write("false");
            }
            else
            {
                Response.Write("true");
            }

            Response.End();
        }

        /// <summary>
        /// 获取第三方回调所需的url
        /// </summary>
        /// <returns></returns>
        private string GetOtherLoginBackUrl()
        {
            string url = "http://www.tongshuya.com/ucenter/otherlogin.aspx";
            url += "?OtherType=" + Convert.ToInt32(UserLoginType).ToString();
            if (Request["urlback"] != null)
            {
                url += "&urlback=" + Server.UrlEncode(Request["urlback"].ToString());
            }
            return url;
        }


        /// <summary>
        /// 生成第三方图片
        /// </summary>
        private void MakeImageByOtherType (){
            
            string result = "/Styles/lib/img/";
            
            switch (UserLoginType)
            {

                //新浪微博处理
                case UserLoginType.SinaWeiBo:
                    result += "logo-SinaWeiBo.png";
                    break;
                //QQ互联处理
                case UserLoginType.QQConnect:
                    result += "logo-QQConnect.png";
                    break;
                //腾讯微博
                case UserLoginType.TencentWeiBo:
                    result += "logo-TencentWeibo.png";
                    break;
                case UserLoginType.RenRen:
                    result += "logo-RenRen.png";
                    break;
            }
            OtherImg.Src = result;
        }
    }
}